package helpers;

import java.util.GregorianCalendar;

public class FinDate {
	private byte day;
	private byte month;
	private short year;
	private boolean initialized = false;
	private static final int MILLISECONDS_IN_DAY = 1000 * 60 * 60 * 24;	
	
	public FinDate(byte day, byte month, short year) {
		if(testInput(day, month, year)) {
			this.day = day;
			this.month = month;
			this.year = year;
			this.initialized = true;
		}		
	}

	public FinDate(int day, int month, int year) {
		this((byte) day, (byte) month, (short) year);
	}

	private boolean testInput(byte d, byte m, short y) {
		GregorianCalendar cal = new GregorianCalendar();
		cal.setLenient(false);
		try {
			cal.set(y, m-1, d);
			cal.getTime();
			System.out.println("OK date!");
		} 
		catch (Exception e){
			System.out.println("Bad date! "+e.getMessage());
			return false;
		}
		return true;		
	}
	
	public byte getDay(){
		return this.day;
	}
	
	public byte getMonth() {
		return this.month;
	}
	
	public short getYear() {
		return this.year;
	}
	
	public boolean isInitialized() {
		return this.initialized;
	}
	
	public int numberOfDaysTo(FinDate date2) {
		int numberOfDaysTo = 0;
		
		if(this.initialized && date2.initialized) {
			GregorianCalendar thisCal = new GregorianCalendar(this.year, this.month, this.day);
			GregorianCalendar daysToCal = new GregorianCalendar(date2.year, date2.month, date2.day);
			
			// Safe to cast to int, milions of days can't happen
			numberOfDaysTo = (int) ((daysToCal.getTimeInMillis() - thisCal.getTimeInMillis())/MILLISECONDS_IN_DAY);
		}
		
		return numberOfDaysTo;
		
	}
	
	/** 
	 * 
	 * @return An integer with the date, compacted. I.e. 10-12-2008 becomes 10122008
	 */
	public int toInt() {
		return year + 10000*month + 1000000*day;
	}
	
	/**
	 * Creates a FinDate from a compact version of a date
	 * @param compactDate integer value, i.e. 10122008 becomes 10-12-2008
	 */
	public FinDate(int compactDate) {
		this(compactDate/1000000, (compactDate%1000000)/10000,  (compactDate%10000));
	}
}
